import React from 'react'
import { connect } from 'dva';
import classnames from 'classnames'
import QueueAnim from 'rc-queue-anim';
import {
    Form,
    Input,
    Button,
    Tabs,
    Icon,
    message,
    Upload,
    Progress
} from 'antd';
import { UrlConfig } from '../../../services/fetch';
import { getBase64, beforeImgUpload, beforeVideoUpload } from '../../../utils/request';
import { sec_to_time } from '../../../utils/Date';

import './Video.scss';

const FormItem = Form.Item;
const { TextArea } = Input;
const TabPane = Tabs.TabPane;
@connect(({ add }) => ({
    add: add
}))
@Form.create({
    onValuesChange: (AddVideo, changedValues, allValues) => {
        AddVideo.dispatch({
            type: 'add/setFields',
            data: changedValues
        })
    },
    /**
     * 从redux初始化Form数据
     */
    mapPropsToFields(props) {
        let data;
        let { articleData } = props.add;
        articleData.forEach((item) => {
            if (item.id == props.add.currentActiveArticle) {
                data = item.data;
            }
        })
        if (articleData.length > 0) {
            return {
                video_title: Form.createFormField({  //标题
                    value: data.video_title,
                }),
                key_word: Form.createFormField({      //关键词
                    value: data.key_word,
                }),
                video_intro: Form.createFormField({   //简介
                    value: data.video_intro,
                }),
                external_links: Form.createFormField({ //外部链接
                    value: data.external_links,
                }),
                video_img: Form.createFormField({    //视频封面图
                    value: data.video_img,
                }),
                video_src: Form.createFormField({    //视频地址
                    value: data.video_src,
                }),
            }
        } else {
            return {}
        }
    }
})
export default class AddVideo extends React.PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            videoError: false,
            imgError: false,
            loadingVideo: false,
            VideoUrl: '',
            imageUrl: '',
            percentVideo: 0,
            percentImage: 0,
            currentHive: '',
            marginLeft: 0,
            marginRight: 0
        }
    }

    componentDidMount() {
        // this.bar.show();
    }

    close = (key) => {
        this.props.dispatch({
            type: 'add/close',
            key: key
        })
    }

    /**
     * 推荐左滑按钮
     */
    left = () => {
        let marginLeft = this.state.marginLeft + 145;
        if (marginLeft >= 0) {
            this.setState({
                marginLeft: 0
            })
        } else {
            this.setState({
                marginLeft: marginLeft
            })
        }
    }

    /**
     * 推荐右滑按钮
     */
    right = () => {
        let marginLeft = this.state.marginLeft - 145;
        let length = (this.props.add.gltjData.length-4)*145
        if(marginLeft<=(-length)){
            this.setState({
                marginLeft: -length
            })
        }else{
            this.setState({
                marginLeft: marginLeft
            })
        }
    }
    /**
     * 图片上传回调
     */
    handleImgChange = (info) => {
        if (info.file.status == 'error') {
            this.setState({ imgError: true });
        }
        if (info.event) {
            this.setState({ percentImage: Math.ceil(info.event.percent) })
        }
        if (info.file.status === 'uploading') {
            this.setState({ loading: true, imgError: false, });
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj, imageUrl => this.setState({
                imageUrl,
                loading: false,
                imgError: false,
            }));


        }
    }

    /**
 * 视频上传回调
 */
    handleVideoChange = (info) => {
        if (info.file.status == 'error') {
            this.setState({ videoError: true });
        }
        if (info.event) {
            this.setState({ percentVideo: Math.ceil(info.event.percent) })
        }
        if (info.file.status === 'uploading') {
            this.setState({ loadingVideo: true, videoError: false, });
            return;
        }
        if (info.file.status === 'done') {
            this.setState({
                VideoUrl: info.file.response.data.video_path,
                imageUrl: this.state.imageUrl == '' ? info.file.response.data.img_path : this.state.imageUrl,
                loadingVideo: false,
                videoError: false
            })
        }
    }
    render() {

        const videoProps = {
            name: "video",
            listType: "picture-card",
            className: "avatar-uploader",
            showUploadList: false,
            action: `${UrlConfig}/fcvideo/Video/uploadVideo`,
            beforeUpload: (file) => {
                return beforeVideoUpload(file, this.state.loadingVideo)
            },
            onChange: this.handleVideoChange
        }

        const uploadVideoButton = () => {
            let text = '点击此处上传';
            if (this.state.loadingVideo) {
                text = '上传中...'
            }
            if (this.state.videoError) {
                text = '上传出错,请从新上传';
            }
            return (
                <div>
                    <Icon type={this.state.loadingVideo ? 'loading' : 'plus'} />
                    <div className="ant-upload-text">{text}</div>
                </div>
            );
        }
        const videoBtnProps = {
            name: "video",
            showUploadList: false,
            action: `${UrlConfig}/fcvideo/Video/uploadVideo`,
            beforeUpload: (file) => {
                return beforeVideoUpload(file, this.state.loadingVideo)
            },
            onChange: this.handleVideoChange
        }
        const imageUrl = this.props.form.getFieldValue('video_img');
        const VideoUrl = this.props.form.getFieldValue('video_src');
        const uploadButton = () => {
            let text = '点击此处上传';
            if (this.state.loading) {
                text = '上传中...'
            }
            if (this.state.imgError) {
                text = '上传出错,请从新上传';
            }
            return (
                <div>
                    <Icon type={this.state.loading ? 'loading' : 'plus'} />
                    <div className="ant-upload-text">{text}</div>
                </div>
            );
        }
        const {
            form: { getFieldDecorator },
        } = this.props;

        let video_title = this.props.form.getFieldValue('video_title');
        video_title = video_title ? video_title : '';
        const titleSuffix = <span className={classnames("titleLength",{red:video_title.length > 60})}>{video_title.length}/60</span>

        let key_word = this.props.form.getFieldValue('key_word');
        key_word = key_word ? key_word : '';
        const keyWordSuffix = <span className={classnames("titleLength",{red:key_word.length > 50})}>{key_word.length}/50</span>

        return (
            <div className="Video">
                <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
                    {getFieldDecorator('video_title')(<Input  prefix={<span className="red">*</span>} suffix={titleSuffix} className="subject" placeholder="请输入标题" />)}
                    {getFieldDecorator('key_word')(<Input className="subject keyword" suffix={keyWordSuffix}  placeholder="请输入关键字" />)}
                    <div className="upload">
                        <div className="video">
                            <div className="title">视频上传<span className="red">（建议尺寸300*170）</span></div>
                            {getFieldDecorator('video_src', {
                                getValueFromEvent: (info) => {
                                    if (info.file.status === 'done') {
                                        this.props.form.setFieldsValue({
                                            video_img: info.file.response.data.img_path,
                                        });
                                        this.props.dispatch({
                                            type: 'add/setFields',
                                            data: {
                                                video_time:sec_to_time(parseInt(info.file.response.data.video_time))
                                            }
                                        })
                                        return info.file.response.data.video_path; 
                                    } else {
                                        return '';
                                    }
                                },
                            })(
                                <Upload
                                    className="Upload"
                                    {...videoProps}
                                >
                                    {VideoUrl && !this.state.loadingVideo ?
                                        <video className="video_pic" src={VideoUrl} controls="controls">
                                            您的浏览器不支持 video 标签。
                                                </video>
                                        : uploadVideoButton()}
                                </Upload>
                            )}
                            {this.state.percentVideo && !this.state.videoError > 0 ? <Progress percent={this.state.percentVideo} status={this.state.percentVideo == 100 ? 'success' : 'active'} /> : ''}
                            {this.state.videoError ? <Progress percent={this.state.percentVideo} status="exception" /> : ''}
                            {/* <Upload
                                {...videoBtnProps}
                            >
                                <Button style={{ marginRight: 20 }} ><Icon type="upload" />本地上传</Button>
                            </Upload> */}
                            {/* <Button onClick={() => {
                                //this.hive('video')
                                window.bar.show('video', 'ggsc');
                            }}>从hive内容库选择</Button> */}
                        </div>
                        <div className="image">
                            <div className="title">封面上传<span className="red">（建议尺寸300*170）</span></div>
                            {getFieldDecorator('video_img', {
                                getValueFromEvent: (info) => {
                                    if (info.file.status === 'done') {
                                        if(info.file.response.data.img_path){
                                            return info.file.response.data.img_path;
                                        }else{
                                            return info.file.response.data;
                                        }
                                    } else {
                                        return '';
                                    }
                                }, 
                            })(
                                <Upload
                                    name="img"
                                    listType="picture-card"
                                    className="avatar-uploader"
                                    showUploadList={false}
                                    action={`${UrlConfig}/fcvideo/Video/uploadImg`}
                                    beforeUpload={(file) => {
                                        return beforeImgUpload(file, this.state.loading)
                                    }}
                                    onChange={this.handleImgChange}
                                >
                                    {imageUrl && !this.state.loading ? <img src={imageUrl} className="video_pic" alt="封面图" /> : uploadButton()}
                                </Upload>
                            )}
                            {this.state.percentImage > 0 && !this.state.imgError ? <Progress percent={this.state.percentImage} status={this.state.percentImage == 100 ? 'success' : 'active'} /> : ''}
                            {this.state.imgError ? <Progress percent={this.state.percentImage} status="exception" /> : ''}
                            {/* <Button onClick={() => {
                                //this.hive('img')
                                window.bar.show('picture', 'ggsc')
                            }}>从hive内容库选择</Button> */}
                        </div>
                    </div>
                    <FormItem label={<span className="title">外部链接<span className="hs">（选填）</span></span>}>
                        {getFieldDecorator('external_links')(<Input placeholder="外部链接" />)}
                    </FormItem>
                </Form>
                <div className="title b-top">相关视频推荐</div>
                <div className="gl-video">
                    <div className="gl-left" onClick={this.left}><Icon type="left" theme="outlined" /></div>
                    <div className="gl-main">
                        <div className="gl-content" style={{ marginLeft: this.state.marginLeft }}>
                            {this.props.add.gltjData.map((item, key) => {
                                return (
                                    <div className="gl-item">
                                        <img className="" src={item.video_img} />
                                        <div className="gl-title">{item.video_title}</div>
                                        <div className="close" onClick={() => {
                                            this.close(key)
                                        }}><Icon className="delete" type="delete" theme="outlined" /></div>
                                    </div>
                                )
                            })}
                        </div>
                    </div>
                    <div className="gl-right" onClick={this.right}><Icon type="right" theme="outlined" /></div>
                </div>
            </div>
        )
    }
}